package com.example.javaproject.thread.juc.blockingqueue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description:
 * <br>Author：tian
 * <br>Time: 2019/3/5 15:28
 */
public class BoundedBuffer {
    private Lock lock = new ReentrantLock();
    /**
     * 写入条件
     */
    private Condition notFull = lock.newCondition();

    /**
     * 读出条件
     */
    private Condition notEmpty = lock.newCondition();

    private Object[] items = new Object[100];

    int putptr, takeptr, count;


    public void put(Object c) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) {
                notFull.await();
            }

            items[putptr] = c;
            putptr++;

            if (putptr == items.length) {
                putptr = 0;
            }

            count++;
            //发出非空signal
            notEmpty.signalAll();
        } finally {
            lock.unlock();
        }
    }


    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.await();
            }

            Object obj = items[takeptr];
            takeptr++;
            if (takeptr == items.length)
                takeptr = 0;

            count--;
            notFull.signalAll();

            return obj;
        } finally {
            lock.unlock();
        }
    }

}
